#include "AiReplacePanelWidget.h"
#include <QTimer>
#include <QScrollBar>

AiReplacePanelWidget::AiReplacePanelWidget(QWidget* parent)
	: QWidget(parent)
	, ui(new Ui::AiReplacePanelWidgetClass())
{
	ui->setupUi(this);
	init();
}

AiReplacePanelWidget::~AiReplacePanelWidget()
{
	delete ui;
}

void AiReplacePanelWidget::init()
{
	createLayout();
}

void AiReplacePanelWidget::createLayout()
{
	m_layout = new QGridLayout(ui->scrollAreaWidgetContents);
	m_layout->setContentsMargins(0, 0, 0, 0);
	m_layout->setSpacing(0);

	// 发型个数
	int hairStylecount = 30;

	for (int i(0); i < hairStylecount; ++i) {
		// 添加发型项，1行3个
		QString hairStyleId = QString::number(i);
		HairStyleItemWidget* hairStyleItem = new HairStyleItemWidget(":/images/1.png", hairStyleId);
		connect(hairStyleItem, &HairStyleItemWidget::sigSelected, this, &AiReplacePanelWidget::onHairStyleItemSelected);
		m_HairStyleMap[hairStyleId] = hairStyleItem;

		int row = i / 3;
		int col = i % 3;

		const int hairStyleIndex = row * 9 + i;
		m_layout->addWidget(hairStyleItem, hairStyleIndex / 3, hairStyleIndex % 3);

		// 添加发色面板
		QString hairColorId = QString("%1").arg(i);
		HairColorPanelWidget* hairColorItem = new HairColorPanelWidget(hairColorId);
		hairColorItem->setHairStyleId(hairStyleId);
		m_HairColorMap[hairColorId] = hairColorItem;

		const int hairColorIndex = 3 * (i + row + 1);
		m_layout->addWidget(hairColorItem, hairColorIndex / 3, 0, 1, 3);
	}

	// 添加弹簧
	int rowCount = m_layout->rowCount();
	QSpacerItem* spacerItem = new QSpacerItem(20, 20, QSizePolicy::Minimum, QSizePolicy::Expanding);
	m_layout->addItem(spacerItem, rowCount, 0, 1, 3);
}

void AiReplacePanelWidget::showEvent(QShowEvent* event)
{
	QWidget::showEvent(event);
}

void AiReplacePanelWidget::onHairStyleItemSelected(const QString& id)
{
	// 设置选中状态
	for (HairStyleItemWidget* item : m_HairStyleMap.values()) {
		if (item->getId() == id) {
			item->setSelected(true);
		}
		else {
			item->setSelected(false);
		}
	}

	// 显示发色面板
	for (HairColorPanelWidget* colorItem : m_HairColorMap) {
		if (colorItem->getHairStyleId() == id) {
			colorItem->show();
		}
		else {
			colorItem->hide();
		}
	}
}